package com.jc.service.vrt;

import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.HttpUtil;
import com.jc.common.util.JSONUtil;
import com.jc.common.util.MD5;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.LogType;
import com.jc.service.apilog.ApiLogService;
import com.jc.service.vrt.model.VrtResult;

@Service
public class VrtServiceImpl implements VrtService {
	private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

	@Value("${vrtclub.notice.url}")
	private String url;

	@Value("${vrt.notice.appkey}")
	private String key;

	@Value("${vrt.notice.code}")
	private String code;


	
	private Long ts = new Date().getTime();

	@Autowired
	ApiLogService apiLogService;

	public VrtResult pushVrtClub(Map<String, Object> noticeMap, String fixurl, LogType logType) {

		noticeMap.put("code", code);
		noticeMap.put("encryptedString", MD5.passmd5("code=" + code + "&ts=" + String.valueOf(ts) + "&key=" + key));
		noticeMap.put("ts", ts);
		try {
			String ret = HttpUtil.post(url + fixurl, noticeMap);

			if (StringUtils.isBlank(ret)) {
				apiLogService.addApiLog(logType, JSONObject.toJSONString(noticeMap), Conclusion.FAIL, "接口返回值为空", "");
				return new VrtResult("通知VRT社区异常, 接口返回值为空 !");
			}
			if (!JSONUtil.isJson(ret)) {
				apiLogService.addApiLog(logType, JSONObject.toJSONString(noticeMap), Conclusion.FAIL, "非JSON格式返回值",
						ret);
				return new VrtResult("通知VRT社区异常, 接口返回值格式错误 : " + ret);
			}

			VrtResult vrtResult = JSONObject.parseObject(ret, VrtResult.class);
			System.out.println(JSONObject.toJSONString(vrtResult));
			if (vrtResult.getReturnCode() != 0) {
				apiLogService.addApiLog(logType, JSONObject.toJSONString(noticeMap), Conclusion.FAIL, "", ret);
				return new VrtResult("通知VRT社区异常, 接口返回值格式错误 returnCode = " + vrtResult.getReturnCode());
			}

			apiLogService.addApiLog(logType, JSONObject.toJSONString(noticeMap), Conclusion.OK, "成功", ret);
			return vrtResult;
		} catch (Exception e) {
			LOGGER.error("通知VRT社区异常, 详情 : {} , {}",e.getMessage(),e);
			String error = e.getMessage();
			if (StringUtils.isNotBlank(error) && error.length() > 200)
				error = error.substring(0, 200);
			apiLogService.addApiLog(logType, JSONObject.toJSONString(noticeMap), Conclusion.FAIL, error, null);
			return new VrtResult("通知VRT社区异常");
		}
	}

}
